package com.gzw.scm.wuyong;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.gson.reflect.TypeToken;
import com.gzw.scm.DEL.DBManager;
import com.gzw.scm.MyApplication;
import com.gzw.scm.R;
import com.gzw.scm.adapter.ZZXFPAdapter;
import com.gzw.scm.base.BaseActivity;
import com.gzw.scm.utils.HttpUtils;
import com.gzw.scm.utils.JsonUtil;
import com.gzw.scm.utils.T;
import com.gzw.scm.utils.UrlUtils;
import com.gzw.scm.view.SwipeRefreshLayout;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/5/2.
 */

public class FHZXActivity extends BaseActivity{
    private Context mContext;
    private RecyclerView mRecyclerView;
    private Toolbar toolbar;
    private Intent intent;
    private Button btn_sure,btn_delete;
    private TextView tv_seleteAll;
    private boolean isCheck = false;
    private DBManager dbManager;
    private List<String> ls_bh,ls_xzbh;
    private ZZXFPAdapter zzxfpAdapter;
    private ProgressDialog mProgressDialog;
    private SwipeRefreshLayout mSwipeLayout;
    private String dataType = "rdcfhzx";

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_fpzzx);
    }

    @Override
    protected void initViews() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        mRecyclerView = (RecyclerView) findViewById(R.id.rv_fp);
        btn_sure = (Button)findViewById(R.id.btn_sure);
        btn_delete = (Button)findViewById(R.id.btn_delete);
        tv_seleteAll = (TextView) findViewById(R.id.ic_head1).findViewById(R.id.tv_selectAll);
    }

    @Override
    protected void initData() {
        mContext = this;
        toolbar.setTitle("周转箱返回中心");
        setSupportActionBar(toolbar);

             /**
        * 刷新框架
        * */
        mRecyclerView.setHasFixedSize(true);
        //设置布局管理器
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        //设置Item增加、移除动画
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        //添加默认分割线
        mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);

        mSwipeLayout.setColor(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        mSwipeLayout.setMode(SwipeRefreshLayout.Mode.DISABLED);
        mSwipeLayout.setLoadNoFull(false);

        dbManager=new DBManager(mContext);
        ls_bh= new ArrayList<>();
        ls_xzbh= new ArrayList<>();

        SelectTask selectTask = new SelectTask();
        selectTask.execute();

//        setData();
    }

    @Override
    protected void initEvents() {
        toolbar.setNavigationOnClickListener(new myOnClick());
        btn_sure.setOnClickListener(new myOnClick());
        btn_delete.setOnClickListener(new myOnClick());
        tv_seleteAll.setOnClickListener(new myOnClick());
    }

    class myOnClick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
                case R.id.btn_sure:
                    senddata();
                    break;
                case R.id.btn_delete:
                    deleteZzxbh();
                    break;
                case R.id.tv_selectAll:
                    if (ls_bh != null) {
                        if (isCheck == false) {
                            // 遍历list的长度，将MyAdapter中的map值全部设为true
                            for (int i = 0; i < ls_bh.size(); i++) {
                                ZZXFPAdapter.getIsSelected().put(i, true);
                            }
                            zzxfpAdapter.notifyDataSetChanged();
                            //改变状态
                            isCheck = true;
                        } else {
                            // 遍历list的长度，将已选的按钮设为未选
                            for (int i = 0; i < ls_bh.size(); i++) {
                                if (ZZXFPAdapter.getIsSelected().get(i)) {
                                    ZZXFPAdapter.getIsSelected().put(i, false);
                                }
                            }
                            zzxfpAdapter.notifyDataSetChanged();
                            isCheck = false;
                        }
                    }
                    break;
                default:
                    finish();
                    break;
            }
        }
    }

    /**
     * 扫描结果
     * */
    @Override
    protected String scanRelust(String code){
        if(code.indexOf("该二维码不符合规则")>0){
            T.showShort(mContext,"该二维码不符合规则");
        }else {
            isScan(code);
        }
//        isScan(code);
        return code;
    };

    /**
     * 判断是否已扫
     * */
    private void isScan(String bh){
        Boolean isExist = dbManager.IsExistZzxbh(bh,dataType,MyApplication.getUserInfo().getDid());
        if(isExist){
            T.showShort(mContext,"该二维码已扫描");
        }else{
            dbManager.addZzxbh(bh,dataType,MyApplication.getUserInfo().getDid());
            setData();
        }
    }

    /**
     * 列表赋值
     * */
    private void setData(){
        ls_bh.clear();
        List<String> lsbh=dbManager.selectFPZzxbh(dataType,MyApplication.getUserInfo().getDid());
        if(lsbh==null){
            return;
        }else {
            ls_bh.addAll(lsbh);
        }
        if(ls_bh==null){
            return;
        }
//        if (mRecyclerView.getAdapter() == null) {
            zzxfpAdapter = new ZZXFPAdapter(ls_bh);
            mRecyclerView.setAdapter(zzxfpAdapter);
//        } else {
//            zzxfpAdapter.notifyDataSetChanged();
//        }
        zzxfpAdapter.setOnRecyclerViewListener(new ZZXFPAdapter.OnRecyclerViewListener() {
            @Override
            public void onItemClick(int position) {
                if(ZZXFPAdapter.getIsSelected().get(position)==true){
                    ZZXFPAdapter.getIsSelected().put(position, false);
                    zzxfpAdapter.notifyDataSetChanged();
                }else{
                    ZZXFPAdapter.getIsSelected().put(position, true);
                    zzxfpAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public boolean onItemLongClick(int position) {
                return false;
            }
        });

    }

    /**
     * 删除周转箱编号
     * */
    private void deleteZzxbh(){
        List<String> lsbh=new ArrayList<>();
        for (int i = 0; i < ls_bh.size(); i++) {
            if (zzxfpAdapter.getIsSelected().get(i)) {
                lsbh.add(ls_bh.get(i));
            }
        }
        if(lsbh.size()==0){
            T.showShort(mContext,"请先选择要删除的编号!");
        }else {
            showDeleteInfo(lsbh);
        }
    }

    /**
     * 删除数据是的提示框
     * */
    private void showDeleteInfo(final List<String> ls_bh){
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("确定要删除这"+ls_bh.size()+"个编号吗?");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dbManager.deleteFPZzxbh(ls_bh,dataType,MyApplication.getUserInfo().getDid());
                setData();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.show();
    }

    /**
     * 上传数据
     * */
    private void senddata(){
        List<String> lsbh=new ArrayList<>();
        for (int i = 0; i < ls_bh.size(); i++) {
            if (zzxfpAdapter.getIsSelected().get(i)) {
                lsbh.add(ls_bh.get(i));
            }
        }
        if(lsbh.size()==0){
            T.showShort(mContext,"请先选择要返回的编号!");
        }else {
            showSendInfo(lsbh);
        }
    }

    /**
     * 删除数据是的提示框
     * */
    private void showSendInfo(final List<String> ls_bh){
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("确定要返回这"+ls_bh.size()+"个周转箱吗?");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                ls_xzbh.clear();
                ls_xzbh.addAll(ls_bh);
                String idStr=new String();
                for (String str:ls_bh){
                    idStr=idStr+str+",";
                }
                idStr = idStr.substring(0, (idStr.length()-1));

                SendTask sendTask = new SendTask();
                sendTask.execute(idStr);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.show();
    }

    /**
     * 上传的数据请求
     * */

    public class SendTask extends AsyncTask<String, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
            mProgressDialog.setCancelable(true);
        }

        protected String doInBackground(String... params) {

            String json="tboxno="+params[0]+"&did="+MyApplication.getUserInfo().getDid()+
                    "&belongid="+String.valueOf(MyApplication.getUserInfo().getBelongId())+
                     "&userid="+MyApplication.getUserInfo().getId()+"&didname="
                     +MyApplication.getUserInfo().getDepartment_name()+"&address=山东";

            return HttpUtils.doPost(UrlUtils.getInstance().getNewJavaUrl("rdcpda.do", "BackCenter"),json);
        }

        @Override
        protected void onPostExecute(final String result) {
            mProgressDialog.dismiss();

            if (result == null || result.length() == 0) {
                T.showShort(mContext, "连接服务器异常");
                return;
            }
            if(result.indexOf("true")>=0){
                T.showShort(mContext,"返回成功");
                dbManager.deleteFPZzxbh(ls_xzbh,dataType,MyApplication.getUserInfo().getDid());
                setData();
            }else if(result.indexOf(",")>=0){
                String dh = JsonUtil.getMsg(result,"order")
                        .toString();
                T.showShort(mContext,dh+"返回失败");
                String[ ] str_Array = dh.split(",");
                List<String> ls = new ArrayList<>();
                for (int i=0;i<str_Array.length;i++){
                    ls.add(str_Array[i]);
                }
                ls_xzbh.removeAll(ls);
                dbManager.deleteFPZzxbh(ls_xzbh,dataType,MyApplication.getUserInfo().getDid());
                setData();

            }else{
                T.showShort(mContext,result);
            }
//            else if(){
//                //{"order":"20170515103514813,20170515103514816,"}
//                String[ ] str_Array = result.split(",");
//                List<String> ls = new ArrayList<>();
//                for (int i=0;i<str_Array.length;i++){
//                    ls.add(str_Array[i]);
//                }
//                ls_bh.removeAll(ls);
//                dbManager.deleteFPZzxbh(ls_bh,dataType);
//                setData();
//            }



        }
    }

    /**
     * 查询可以返回中心的数据请求
     * */

    public class SelectTask extends AsyncTask<String, Void, String> {
        protected String doInBackground(String... params) {
            String json="did="+MyApplication.getUserInfo().getDid();
            return HttpUtils.doPost(UrlUtils.getInstance().getNewJavaUrl("rdcpda.do", "SelectBackCenter"),json);
        }

        @Override
        protected void onPostExecute(final String result) {
            //[{"name":"20170519143055042"},{"name":"20170519143055053"},{"name":"19990314033300345"},{"name":"19990314033300348"},{"name":"19990314033300351"}]
            if (result == null || result.length() == 0) {
                T.showShort(mContext, "连接服务器异常");
                setData();
                return;
            }
            try{
                List<FhzxInfo> list_bh = JsonUtil.getPersons(result, new TypeToken<List<FhzxInfo>>() {
                }.getType());
                if (list_bh.size()!=0){
                    for(FhzxInfo fhzxInfo:list_bh){
                        String bh = fhzxInfo.getName();
                        if(!dbManager.IsExistZzxbh(bh,dataType,MyApplication.getUserInfo().getDid())){
                            dbManager.addZzxbh(bh, dataType,MyApplication.getUserInfo().getDid());
                        }
                    }
                }
            }catch (Exception e){
               T.showLong(mContext,result);
            }

            setData();
        }
    }

  class FhzxInfo{
      private String name;

      public String getName() {
          return name;
      }

      public void setName(String name) {
          this.name = name;
      }
  }

}